﻿using Ionic.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace SubtitleDownloader
{
	public static class Utils
	{
		public static string GetHtml(Uri uri, out Uri responseUri)
		{
			string ret = null;
			responseUri = null;
			var webRequest = HttpWebRequest.Create(uri);
			try {
				var webResponse = (HttpWebResponse)webRequest.GetResponse();
				if (webResponse.StatusCode == HttpStatusCode.OK) {
					responseUri = webResponse.ResponseUri;
					using (var responseStream = new StreamReader(webResponse.GetResponseStream())) {
						ret = responseStream.ReadToEnd();
					}
				}
			} catch { }
			return ret;
		}

		public static string GetHtml(Uri uri)
		{
			Uri temp;
			return GetHtml(uri, out temp);
		}

		public static string DownloadFile(Uri uri)
		{
			string ret = null;
			try {
				var tempFile = Path.GetTempFileName();
				using (var webClient = new WebClient())
				webClient.DownloadFile(uri, tempFile);
				ret = tempFile;
			} catch { }
			return ret;
		}

		public static string Extract(string file, bool deleteOriginal = true)
		{
			string ret = null;
			if (file != null) {
				if (ZipFile.IsZipFile(file, false)) {
					try {
						var tempPath = Path.GetTempPath();
						var zipFile = ZipFile.Read(file);
						if (zipFile.Entries.Count > 0) {
							var zipEntry = zipFile[0];
							zipEntry.Extract(tempPath, ExtractExistingFileAction.OverwriteSilently);
							ret = Path.Combine(tempPath, zipEntry.FileName);
						}
						if (deleteOriginal) {
							zipFile.Dispose();
							File.Delete(file);
						}
					} catch { }
				}
			}
			return ret;
		}

		public static string BrowseForFolder()
		{
			string ret = null;
			var folderBrowser = new FolderBrowserDialog();
			folderBrowser.ShowNewFolderButton = false;
			if (folderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
				ret = folderBrowser.SelectedPath;
			return ret;
		}

		public static double GetSimilarityIndex(string str1, string str2)
		{
			var str1Split = Regex.Split(str1, "[^a-zA-Z0-9]+");
			var str2Split = Regex.Split(str2, "[^a-zA-Z0-9]+");

			double minLength = Math.Min(str1Split.Length, str2Split.Length);
			double maxLength = Math.Max(str1Split.Length, str2Split.Length);

			var matches = 0.0;

			for (var i = 0; i < str1Split.Length; i++) {
				if (str2Split.Contains(str1Split[i]))
					matches++;
			}

			return (matches / maxLength) * 100;
		}

		public static IEnumerable<VideoItem> GetVideoItems(string folder, bool filterFilesWithSubtitles = true)
		{
			if (Directory.Exists(folder)) {
				foreach (var file in Directory.EnumerateFiles(folder, "*.*", SearchOption.AllDirectories).Where(s =>
					s.EndsWith(".avi", StringComparison.OrdinalIgnoreCase) ||
					s.EndsWith(".mkv", StringComparison.OrdinalIgnoreCase))) {
					var cont = false;
					foreach (var filter in Data.Instance.FileNameFilters) {
						if (file.ToLower().Contains(filter)) {
							cont = true;
							break;
						}
					}
					if (cont)
						continue;
					var videoItem = new VideoItem(file);
					if (!filterFilesWithSubtitles ? true : !videoItem.HaveSubtitles)
						yield return videoItem;
				}
			}
		}
	}
}
